package demo3;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

class MyStack {
    Queue<Integer> queue1;
    Queue<Integer> queue2;

    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }

    public void push(int x) {
        if(empty()) {
            queue1.offer(x);
        } else if(queue1.isEmpty()) {
            queue1.offer(x);
        } else {
            queue2.offer(x);
        }
    }

    private void offerAndPoll(Queue x, Queue y) { //x 有元素，y 为空队列
        for(int i=0; i<x.size()-1; i++) {
            y.offer(x.poll());
        }
    }

    public int pop() {
        if(!queue1.isEmpty()) {
            offerAndPoll(queue1,queue2);
            return queue1.poll();
        } else {
            offerAndPoll(queue2,queue1);
            return queue2.poll();
        }
    }

    public int top() {
        int ret = 0;
        if(!queue1.isEmpty()) {
            offerAndPoll(queue1,queue2);
            ret = queue1.poll();
            queue2.offer(ret);
        } else {
            offerAndPoll(queue2,queue1);
            ret = queue2.poll();
            queue1.offer(ret);
        }
        return ret;
    }

    public boolean empty() {
        if(queue1.isEmpty() && queue2.isEmpty()) {
            return true;
        }

        return false;
    }
}
